<template>
  <div :edit="form.editInfo.isEdit" :renewal="form.renewal.isRenewal">
    <el-form label-position="top" :model="form" :rules="rules" ref="formRef" label-width="120px" :validate-on-rule-change="false">
      <template v-if="form.editInfo.isEdit || form.renewal.isRenewal">
        <!-- <el-form-item label="岗位">{{ form.editInfo.title }}</el-form-item> -->
        <!-- 姓名 -->
        <el-form-item :label="$t('contract_signed.employee_name')"
          ><span class="label_show">{{ form.editInfo.name || form.renewal.name }}</span>
        </el-form-item>
      </template>
      <template v-else>
        <!-- 选择员工 -->
        <el-form-item :label="$t('contract.select_employee_name')" prop="employee_name.value">
          <el-select
            class="qf_select"
            v-model="form.employee_name.value"
            filterable
            remote
            clearable
            :remote-method="remoteMethod"
            :placeholder="$t('contract.select_employee_name_placeholder')"
          >
            <el-option v-for="item in employeeNameOptions" :key="item" :label="item.value" :value="item.key"> </el-option>
          </el-select>
        </el-form-item>
      </template>
      <!-- 合同编号ru -->
      <el-form-item :label="$t('contract.contract_number')" prop="contract_no.value">
        <el-input
          class="qf_input"
          :placeholder="$t('contract.contract_number_placeholder')"
          v-model="form.contract_no.value"
        ></el-input>
      </el-form-item>

      <!-- 合同类型 -->
      <el-form-item :label="$t('contract.contract_type')" prop="contract_type.value">
        <el-select
          clearable
          class="qf_select"
          v-model="form.contract_type.value"
          :placeholder="$t('contract.contract_status_placeholder')"
        >
          <el-option v-for="item in contractTypeOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>

      <!-- 合同期限(年) -->
      <el-form-item :label="$t('contract.contract_period_year')" v-if="form.contract_period.isShow" prop="contract_period.value">
        <el-input class="qf_input" @change="contractPeriodChange" v-model.trim="form.contract_period.value"></el-input>
      </el-form-item>
      <!-- 合同开始时间 -->
      <el-form-item :label="$t('contract.contract_start')" prop="contract_start.value">
        <el-date-picker
          @change="startDateChange"
          class="qf_date"
          :disabled-date="setStartDateDisabled"
          v-model="form.contract_start.value"
          type="date"
          :placeholder="$t('contract.contract_start_placeholder')"
          :value-format="format"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 合同结束时间 -->
      <el-form-item :label="$t('contract.contract_end')" v-if="form.contract_end.isShow" prop="contract_end.value">
        <el-date-picker
          class="qf_date"
          :disabled-date="setEndDateDisabled"
          v-model="form.contract_end.value"
          type="date"
          :placeholder="$t('contract.contract_end_placeholder')"
          :default-value="form.contract_start.value"
          :value-format="format"
        >
        </el-date-picker>
      </el-form-item>
      <!-- 合同签约公司 -->
      <el-form-item :label="$t('contract.contract_company')" prop="contract_company_id.value">
        <div class="contract_company">
          <el-select
            clearable
            class="qf_select"
            v-model="form.contract_company_id.value"
            :placeholder="$t('contract.contract_company_placeholder')"
          >
            <el-option v-for="item in contractCompanies" :key="item.value" :label="item.value" :value="item.key"> </el-option>
          </el-select>
          <el-button circle @click="openAddCompany">
            <el-icon><CirclePlus /></el-icon>
          </el-button>
        </div>
      </el-form-item>
      <!-- 合同状态 -->
      <el-form-item :label="$t('contract.contract_status')" prop="contract_status.value">
        <el-select
          clearable
          class="qf_select"
          v-model="form.contract_status.value"
          :placeholder="$t('contract.contract_status_placeholder')"
        >
          <el-option v-for="item in contractStatus" :key="item.value" :label="item.value" :value="item.key"> </el-option>
        </el-select>
      </el-form-item>
      <!-- 合同签订时间 -->
      <el-form-item :label="$t('contract.contract_date')" prop="contract_date.value">
        <el-date-picker
          class="qf_date"
          :disabled-date="setRenewalDateDisabled"
          v-model="form.contract_date.value"
          type="date"
          :placeholder="$t('contract.contract_date_placeholder')"
          :value-format="format"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="是否到期提醒" prop="remind" style="display: none">
        <el-switch active-value="1" inactive-value="0" disabled v-model="form.remind.value" />
      </el-form-item>
      <template v-if="form.type_id.value != 'noSigned'">
        <el-form-item
          v-if="form.editInfo.isEdit || form.renewal.isRenewal"
          label="上份合同解除原因"
          prop="last_terminate_reason.value"
        >
          <el-input
            class="qf_textare"
            v-model="form.last_terminate_reason.value"
            maxlength="500"
            :autosize="{ minRows: 4, maxRows: 6 }"
            show-word-limit
            type="textarea"
          />
        </el-form-item>
      </template>

      <!-- <el-form-item style="display:none">
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
        <el-button @click="resetForm(formRef)">重置</el-button>
      </el-form-item> -->
    </el-form>
  </div>
  <companyComponent
    ref="companyComponentRef"
    :show-add-form="showAddCompany"
    :is-quick-add="isAddCompanyComponent"
    @companyChangeEvent="companyComponentChange"
  ></companyComponent>
</template>  

<script lang="ts" setup>
import { reactive, ref, defineProps, computed, onMounted, defineEmits, nextTick, watch, getCurrentInstance } from "vue";
import { type FormInstance, type FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";

import {
  Path,
  getOrgsMenus,
  getUsers,
  getContractManageOptions,
  saveContractManageOptions,
  lang
} from "@/api/modules/personalManagementApi/contract";
import { ResultEnum } from "@/enums/httpEnum";

import companyComponent from "../../contractCompany/index.vue";

import useDateFormat from "@/hooks/useDateFormat";
import { format } from "echarts/core";
import { deleteFiles } from "@/api/modules/sysManage/personnel";

const { format } = useDateFormat();
lang(getCurrentInstance);
const companyComponentRef = ref();
const formRef = ref();
const props = defineProps(["modelValue"]);
const formUpadate = ref(4321423);

let $emit = defineEmits<{
  (event: "saveSuccess", val: any): void;
}>();

const orgList = ref([]);
const cascaderProps = ref({
  value: "org_id",
  label: "title"
});

const userOptions = ref([]);
const contractTypeOptions = ref([]);
const contractCompanies = ref([]);
const contractStatus = ref([]);
const contractPeriod = ref([]);

const formSize = ref("default");
const form = reactive({
  cascader: {
    value: [],
    label: "",
    options: []
  },
  employee_name: {
    value: "",
    label: "",
    options: []
  },
  contract_no: {
    value: "",
    label: lang("contract.contract_number") //"合同编号"
  },
  contract_type: {
    value: "",
    label: lang("contract.contract_type"), //"合同类型",
    options: []
  },
  contract_period: {
    value: "",
    label: lang("contract.contract_period_year"), // "合同期限",
    isShow: true
  },
  contract_start: {
    value: "",
    label: lang("contract.contract_start") // "合同开始时间"
  },
  contract_end: {
    value: "",
    label: lang("contract.contract_end"), //"合同结束时间",
    isShow: true
  },
  contract_company_id: {
    value: "",
    label: lang("contract.contract_company"), // "合同签约公司",
    options: []
  },
  contract_status: {
    value: "",
    label: lang("contract.contract_status"), //  "合同状态",
    options: []
  },
  contract_date: {
    value: "",
    label: lang("contract.contract_date") // "合同签订时间"
  },
  last_terminate_reason: {
    value: "",
    label: lang("contract.last_terminate_reason") // "上一份合同解除原因"
  },
  remind: {
    value: "1",
    label: "是否到期提醒"
  },
  editInfo: {
    name: "",
    title: "",
    isEdit: false,
    minStartDate: ""
  },
  renewal: {
    name: "",
    title: "",
    isRenewal: false
  },
  userOptions: {
    value: []
  },
  type_id: {
    value: ""
  }
});

const validateNumber = (rule: any, value: any, callback: any) => {
  let reg = /(^(([1-9]\d?)|100)$)|(^[0-9][1-9]?\.\d{1}$)/;
  if (value === "") {
    //"请填写合同期限"
    callback(new Error(lang("contract.contract_period_required")));
    return;
  }
  if (!reg.test(value)) {
    // 合同期范围为1-100的数字"
    callback(new Error(lang("contract.contract_period_range")));
    return;
  }
  if (Number(value) <= 0) {
    callback(new Error(lang("contract.contract_period_range")));
    return;
  }

  callback();
};

const rules = reactive<FormRules<RuleForm>>({
  "cascader.value": [{ required: true, message: "请选择岗位", trigger: "change" }],
  "employee_name.value": [
    {
      required: true,
      message: lang("contract.select_employee_name_placeholder"), // "请选择岗位员工",
      trigger: "change"
    }
  ],
  "contract_type.value": [
    {
      required: true,
      message: lang("contract.contract_type_placeholder"), //  "请选择合同类型",
      trigger: "change"
    }
  ],
  "contract_start.value": [
    {
      type: "date",
      required: true,
      message: lang("contract.contract_start_placeholder"), // "请选择合同开始时间",
      trigger: "change"
    }
  ],
  "contract_end.value": [
    {
      type: "date",
      required: true,
      message: lang("contract.contract_end_placeholder"), //  "请选择合结束时间",
      trigger: "change"
    }
  ],
  "contract_company_id.value": [
    {
      required: true,
      message: lang("contract.contract_company_placeholder"), //  "请选择合同公司",
      trigger: "change"
    }
  ],
  "contract_period.value": [
    {
      // type: "date",
      required: true,
      // message: "请选择合同期限",
      trigger: "change",
      validator: validateNumber
    }
  ],
  "contract_status.value": [
    {
      required: true,
      message: lang("contract.contract_status_placeholder"), // "请选择合同状态",
      trigger: "change"
    }
  ],
  "contract_date.value": [
    {
      required: true,
      message: lang("contract.contract_date_placeholder"), //  "合同签订时间",
      trigger: "change"
    }
  ]
});

//异步获取员工
// 异步筛选员工数据
const employeeNameOptions = reactive([]);
const remoteMethod = param => {
  let employeeNameList = JSON.parse(JSON.stringify(form.userOptions.value || []));
  let employeeNameLength = employeeNameList?.length || 0;

  let splitEmployeeNameList = [];
  if (employeeNameLength < 30) {
    employeeNameOptions.splice(0, Infinity, ...employeeNameList);
    return;
  }

  const fliter = (param, list) => {
    return new Promise((resolve, rejcet) => {
      let ids = [];
      param = param.replace(" ", "");
      if (param.length == 0) {
        resolve([]);
      }
      list.filter(item => {
        let value = item.value;
        if (new RegExp(param, "ig").test(value)) {
          ids.push(item);
        }
      });
      resolve(ids);
    });
  };

  fliter(param, employeeNameList).then(res => {
    employeeNameOptions.splice(0, Infinity, ...res);
  });
};

//选择岗位
const cascaderChange = value => {
  let data = {
    org_company: form.cascader.value["0"],
    org_department: form.cascader.value["1"],
    org_title: form.cascader.value["2"]
  };
  getUsers(data).then(res => {
    form.employee_name.value = "";
    let options = res.data;
    options.map(item => {
      let data = {
        value: item.key,
        label: item.value
      };

      return { ...data };
    });
    userOptions.value = { ...options };
  });
};
//选择合同期限
const contractPeriodChange = value => {
  if (form.contract_period.value) {
    startDateChange(form.contract_start.value);
  } else {
    form.contract_end.value = "";
  }
};

//选择合同类型- 联动 结束日期校验
const contractTypeChange = value => {
  if (value == 3) {
    form.contract_period.isShow = false;
    form.contract_end.isShow = false;
    form.contract_period.value = 100;
    //选择了无固定期合同 结束日期不在校验，不显示
    startDateChange(form.contract_start.value);
    rules["contract_end.value"][0].required = false;
  } else {
    form.contract_period.isShow = true;
    form.contract_end.isShow = true;
    // form.contract_period.value = "";
    if (form.contract_period.value == 100) {
      //不是无固定期 、合同期限是 100年 合同期限置空
      form.contract_period.value = "3";
    }

    rules["contract_end.value"][0].required = true;
    startDateChange(form.contract_start.value);
  }
  formRef.value.clearValidate();
};

//开始时间禁用范围
const setStartDateDisabled = time => {
  // if (form.renewal.isRenewal) {
  //   //续签状态下开始日期等于结束日期，开始时间的前一天禁用
  //   return time.getTime() < new Date(form.contract_start.value).getTime() - 3600 * 1000 * 24;
  // }
  // if (form.editInfo.isEdit) {
  //   //合同记录 编辑状态，开始时间不小于 开始时间的前一天，

  //   return time.getTime() < new Date(form.contract_start.value ?? dayjs().format("YYYY-MM-DD")).getTime() - 3600 * 1000 * 24;
  // }
  //正常情况下不能小于昨天
  return false;
  return time.getTime() < new Date().getTime() - 3600 * 1000 * 24;
};
//结束时间禁用范围
const setEndDateDisabled = time => {
  return false;
  if (form.renewal.isRenewal) {
    //续签状态下结束日期不能小于续签开始日期
    return time.getTime() < new Date(form.contract_start.value).getTime();
  }
  if (form.editInfo.isEdit) {
    //合同记录 编辑状态 结束时间不小于开始时间，但不能是开始时间
    return time.getTime() < new Date(form.contract_start.value).getTime();
  }

  //正常情况下不能小于开始时间(以本机时间为主)
  return false;
  return time.getTime() < (form.contract_start.value || new Date().getTime());
};

//签订时间禁用范围 签订时间不能小于今天
const setRenewalDateDisabled = time => {
  return false;
  return time.getTime() < new Date().getTime() - 3600 * 1000 * 24;
};
// 开始时间联动
const startDateChange = curDate => {
  console.log(form.contract_start.value);

  if (!form.contract_start.value) {
    return;
  }
  let range = form.contract_period.value || 0;
  range = range * 365;
  let endTime = dayjs(curDate).add(range, "day").format("YYYY-MM-DD");
  form.contract_end.value = endTime;
};
//表单验证
const formRefValid = () => {
  formRef.value.validate().then(res => {
    let formData = {};
    Object.keys(form).map(item => {
      if (item == "contract_date" || item == "contract_start") {
        formData[item] = dayjs(form[item].value).format("YYYY-MM-DD");
      } else {
        formData[item] = form[item].value;
      }
    });

    if (formData.employee_name ?? true) {
      formData["user_id"] = formData.employee_name;
    }

    saveContractManageOptions(JSON.parse(JSON.stringify(formData))).then(res => {
      if (res.code == ResultEnum.SUCCESS) {
        $emit("saveSuccess", {});
      } else {
        ElMessage.error(res.message);
      }
    });
  });
};

const init = () => {
  console.log(JSON.stringify(props.modelValue));
  nextTick(() => {
    Object.assign(form, props.modelValue);
    getOrgsMenus("").then(res => {
      orgList.value = res.data;
    });
    getContractManageOptions("").then(res => {
      console.log(res);
      //合同类型 options
      let typeOptions = res.data.contract_type;
      typeOptions.map(item => {
        // let data = {
        //   value: item.key,
        //   label: item.value
        // };
        item["label"] = item.value;
        item["value"] = item.key;

        // return { ...data };
      });

      contractTypeOptions.value = { ...typeOptions };
      console.log(contractTypeOptions);

      //合同签署公司options
      let contractCompaniesOptions = res.data.contract_companies;
      contractCompaniesOptions.map(item => {
        let data = {
          value: item.key,
          label: item.value
        };
        return { ...data };
      });

      contractCompanies.value = contractCompaniesOptions;

      //合同状态options
      let contractStatusOptions = res.data.contract_status;
      contractStatusOptions.map(item => {
        let data = {
          value: item.key,
          label: item.value
        };
        return { ...data };
      });
      contractStatus.value = contractStatusOptions;

      // let contractPeriodOptions = res.data.contract_period;
      // contractPeriodOptions.map(item => {
      //   let data = {
      //     value: item.key,
      //     label: item.value
      //   };
      //   return { ...data };
      // });
      // contractPeriod.value = contractPeriodOptions;
    });
  });
};

const formClear = () => {
  return new Promise((resolve, reject) => {
    nextTick(() => {
      formRef.value.resetFields();
      setTimeout(() => {
        formRef.value.clearValidate();
        resolve("");
      }, 100);
    });
  });
};

//激活 添加公司组件
const isAddCompanyComponent = ref<boolean>(true);
const showAddCompany = ref<boolean>(false);

//点击显示添加公司功能
const openAddCompany = () => {
  showAddCompany.value = true;
  companyComponentRef.value.show();
};

//公司管理组件 操作后的emit过来的event
const companyComponentChange = () => {
  init();
};

onMounted(() => {
  init();
});
//设置表单数据
const setformData = () => {
  if (form.renewal.isRenewal) {
    //续签状态下开始日期等于结束日期+1天
    form.contract_start.value = dayjs(form.renewal.minStartDate).add(1, "day").format("YYYY-MM-DD");
    contractPeriodChange(); //计算合同结束日期
  }
};

//wacther 选择无固定期限时不显示 合同期限
watch(
  () => form.contract_type.value,
  (nval, oval) => {
    contractTypeChange(nval);
  }
);
watch(
  () => form.editInfo.isEdit,
  (nval, oval) => {
    // console.log(form.editInfo.isEdit);
    // console.log(form.editInfo.minStartDate);
    // console.log(dayjs(form.editInfo.minStartDate).add(1, "day").format("YYYY-MM-DD"));
    // if (form.editInfo.isEdit) {
    //   //续签状态下开始日期等于结束日期
    //   console.log(dayjs(form.editInfo.minStartDate).add(1, "day").format("YYYY-MM-DD"));
    //   form.contract_start.value = dayjs(form.editInfo.minStartDate).add(1, "day").format("YYYY-MM-DD");
    // }
  }
);
watch(
  () => form.renewal.isRenewal,
  (nval, oval) => {
    setformData();
  }
);

defineExpose({
  valid: formRefValid,
  reset: formClear,
  setformData: setformData
});
</script>

<style lang="scss" scoped>
:deep(.el-form-item__content) {
  .el-input,
  .el-cascader {
    flex: 1;
  }
}
.contract_company {
  flex: 1;
  display: flex;
  justify-content: flex-start;
  align-items: flex-end;
}
</style>